#include "rtcp.h"
#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>  // 添加: 包含inet_pton函数的头文件

RTCP::RTCP() : port(0), addr(""), sockfd(-1) {
    // 默认构造函数，初始化成员变量
}

RTCP::~RTCP() {
    // 析构函数，关闭socket
    if (sockfd != -1) {
        close(sockfd);
    }
}

int RTCP::init(int port, const std::string& addr) {
    this->port = port;
    this->addr = addr;

    // 打印初始化信息
    std::cout << "RTCP initialized with port: " << port << " and address: " << addr << std::endl;

    // 调用UDP初始化
    if (udp_init() != 0) {
        return -1;  // UDP初始化失败
    }

    // 返回成功状态码
    return 0;
}

int RTCP::udp_init() {
    // 创建UDP socket
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        std::cerr << "Failed to create UDP socket" << std::endl;
        return -1;
    }

    // 设置服务器地址结构
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    if (inet_pton(AF_INET, addr.c_str(), &server_addr.sin_addr) <= 0) {
        std::cerr << "Invalid address or address not supported" << std::endl;
        close(sockfd);
        return -1;
    }

    // 绑定socket到地址
    if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        std::cerr << "Bind failed" << std::endl;
        close(sockfd);
        return -1;
    }

    std::cout << "UDP server bound to " << addr << ":" << port << std::endl;
    return 0;
}